package com.demo.security.impl;

import java.util.Collection;
import java.util.Date;

import com.demo.security.access.model.PlatformUser;
import com.demo.security.access.model.SecurityUser;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户基本信息
 * 基于SpringSecurity实现
 * 增加PlatformUser接口为容器中得到用户信息得到依据
 * 另:该类不基于Web容器,则不应从SecurityUtil中取得用户
 * 
 * @author ryuu.kk
 *
 */
public class UserDetailsWrapper<T extends SecurityUser, M> implements UserDetails, PlatformUser<M> {
	
	/**
	 * 序列化ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 密码，由UserDetailServiceImpl注入
	 * @deprecated see SecurityUser
	 */
	//@Deprecated 
	//private String password;
	
	/**
	 * 用户名，由UserDetailServiceImpl注入
	 * @deprecated see SecurityUser
	 */
	//@Deprecated 
	//private String username;
	
	/**
	 * 被授予的角色，由UserDetailServiceImpl注入
	 */
	private Collection<GrantedAuthority> authorities;
	
	/**
	 * 在用户信息中提供业务层的用户对象
	 * 以便于通过框架来访问用户对象
	 */
	private T securityUser;
	
	/**
	 * 平台模型,可以是securityUser或平台自定义对象
	 * 目的是使这些对象可以由安全框架进行传递
	 */
	private M platformUser;
	
	/**
	 * 构造方法
	 * @param t SecurityUser类的继承类
	 * @param authorities Collection<GrantedAuthority>
	 */
	public UserDetailsWrapper(T t, M m, Collection<GrantedAuthority> authorities) {
		this.securityUser = t;
		this.platformUser = m;
		this.authorities = authorities;
	}
	@Override
	public Collection<GrantedAuthority> getAuthorities() {
		return this.authorities;
	}

	public void setAuthorities(Collection<GrantedAuthority> authorities) {
		this.authorities = authorities;
	}

	@Override
	public String getPassword() {
		return securityUser.getPassword();
	}

	@Override
	public String getUsername() {
		return securityUser.getUserName();
	}
	
	@Override
	public String getUserSalt() {
		return securityUser.getSalt();
	}

	@Override
	public boolean isAccountNonExpired() {
		return securityUser.getExpireDay().getTime() >= (new Date()).getTime();
	}

	@Override
	public boolean isAccountNonLocked() {
		return securityUser.getIsValid();
	}
	
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	
	@Override
	public boolean isEnabled() {
		return securityUser.getEnabled();
	}
	
	public void setUser(T t) {
		this.securityUser = t;
	}

	public T getCurrentUser() {
		return securityUser;
	}

	@Override
	public M getModel() {
		return this.platformUser;
	}
}
